/**
 * @基于邮箱的文件平台
 * @author Wang,Gao,Jia
 * @main class:display
 * @created on 2009
 */

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.mail.internet.MimeMessage;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.tree.DefaultMutableTreeNode;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.ImageIcon;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.JPopupMenu;
import java.awt.event.*;
import javax.swing.JButton;

import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.mail.*;

import com.jgoodies.forms.factories.DefaultComponentFactory;

public class display extends JFrame {

	private JTextField textField;
	private JList list;
	public static JTree tree;//文件树
	public ArrayList<DefaultMutableTreeNode> s = new ArrayList<DefaultMutableTreeNode>();
	public ArrayList<String> t = new ArrayList<String>();
	public Vector<String> data = new Vector<String>();
	public static String string = null;
	public static TreePath path;//树区域
	public static String pathstring = null;
	public static String date = new String();
	
	//****
	public String leaves = new String();
	public static String downpathstring = new String();
	public static String downstring = new String();

	analyser ana = new analyser();

	/**
	 * Launch the application
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			display frame = new display();
			frame.setTitle("基于邮箱的文件共享平台");
			int w = (int) Toolkit.getDefaultToolkit().getScreenSize()
					.getWidth();
			int h = (int) Toolkit.getDefaultToolkit().getScreenSize()
					.getHeight();
			frame.setLocation((w - frame.getSize().width) / 2, (h - frame
					.getSize().height) / 2);

			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame
	 */
	public display() {

		super();
		//System.out.println(ana.message.length);
		getContentPane().setLayout(null);
		setBounds(100, 100, 644, 533);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		list = new JList();
		tree = createTree();//得到JTree对象

		//tree.setSelectionRow(0);

		//tree设置
		DefaultTreeCellRenderer render = new DefaultTreeCellRenderer();
		render.setClosedIcon(new ImageIcon("resources/folder_star.png"));
		render.setOpenIcon(new ImageIcon("resources/folder_star.png"));
		render.setLeafIcon(new ImageIcon("resources/page_white_star.png"));
		tree.setCellRenderer(render);
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {

				int lev = e.getPath().getPathCount();
				path = e.getPath();
				String str1 = e.getPath().toString();
				String str2 = str1.replace(", ", "/");
				pathstring = str2.substring(1, str2.length() - 1);

				System.out.println(pathstring);
				
				textField.setText("/" + pathstring);
				textField.setFont(new Font("Alias", Font.BOLD, 12));
				string = e.getPath().getLastPathComponent().toString();

				data.clear();
				if (list != null)
					list.removeAll();
				for (int i = 0; i < ana.node.size(); i++) {
					if (string.equals(ana.node.get(i).uppername)
							&& lev == ana.node.get(i).level)
						data.add(ana.node.get(i).name);
					//list.add(ana.node.get(i).name,null);	    
				}

				final JPopupMenu popup = new JPopupMenu();
				JMenuItem modify = new JMenuItem("下载");

				modify.setActionCommand("下载");
				modify.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						downpathstring = pathstring;
						downstring = string;
						new SaveFiledialog();
					}
				});
				JMenuItem property = new JMenuItem("属性");
				property.setActionCommand("属性");
				property.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						// new SaveFiledialog();
						property pro = new property();
						pro.setVisible(true);
					}
				});

				JMenuItem upload = new JMenuItem("上传");
				upload.setActionCommand("上传");
				upload.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						// new SaveFiledialog();
						
						//如何处理路径问题
						//
						FileDialog my1 = new FileDialog(display.this, "打开",
								FileDialog.LOAD);
						my1.setVisible(true);

						String mailbody = "" + " ";
						String subject = new String();
						subject = "/" + pathstring;
						int index = subject.indexOf(".");
						if (index == -1) {
							subject = subject.substring(5) + "/"
									+ my1.getFile();
							System.out.println(subject);
						} else {
							int index2 = subject.lastIndexOf("/");
							subject = subject.substring(5, index2 + 1)
									+ my1.getFile();
							System.out.println(subject);
						}

						sendMail themail = new sendMail("smtp.sina.com.cn");
						themail.setNeedAuth(true);

						if (themail.setSubject(subject) == false)
							return;
						if (themail.setBody(mailbody) == false)
							return;
						if (themail.setTo("wangq_30@sina.com") == false)
							return;
						if (themail.setFrom("wangq_30@sina.com") == false)
							return;
						if (themail.addFileAffix(my1.getDirectory()
								+ my1.getFile()) == false)
							return;
						themail.setNamePass("wangq_30", "901170");
						if (themail.sendout() == false)
							return;
						try {
							PrintWriter pw = new PrintWriter(
									new FileOutputStream("name.txt", true),
									true);
							pw.println(subject + ";");//时间没办法写进去怎么办？？？？
							pw.close();
						} catch (Exception ee) {
							ee.printStackTrace();
						}
						dispose();
						display dis = new display();
						dis.setVisible(true);
						tree.addSelectionPath(path);
						//以上是处理上传路径的问题
					}
				});
				JMenuItem zhankai = new JMenuItem("展开");
				zhankai.setActionCommand("展开");
				zhankai.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						tree.expandPath(path);
					}
				});
				popup.add(zhankai);
				popup.add(modify);
				popup.add(upload);
				popup.add(property);

				
				// 1: 左键选中然后再右键去操作——————————能否变成邮件直接选中、操作？
				tree.addMouseListener(new MouseAdapter() {
					public void mousePressed(MouseEvent e) {
						if (e.getButton() == e.BUTTON3) { //BUTTON3是鼠标右键
							DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
									.getLastSelectedPathComponent();

							popup.show(e.getComponent(), e.getX(), e.getY());
							// System.out.println("nihao");
							//popup
							
						}
					}
				});

				list.setListData(data);

			}
		});

		tree.setBounds(0, 33, 174, 400);
		getContentPane().add(tree);

		list.setCellRenderer(new MyCellRenderer());
		list.setBounds(177, 33, 450, 400);
		JLabel label2 = new JLabel();
		label2.setBounds(0, 0, 450, 400);
		label2.setIcon(new ImageIcon("resources/beijing.jpg"));
		list.add(label2);
		
		
		//右边面板的事件处理
		list.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent ex) {
				
				//System.out.println("ishere?");
				int num = list.getSelectedIndex();
				//System.out.println(num+"  "+ana.looktype(string).leaf.size());
				
				leaves = ana.looktype(string).leaf.get(num).toString();
				//System.out.println(leaves);
				downpathstring = pathstring+"/"+leaves;
				downstring = leaves;
				System.out.println("2222pathstring:"+downpathstring);
				System.out.println("2222string:"+downstring);
				
				
				
				/*
				int lev = ex.getPath().getPathCount();
				path = ex.getPath();
				String str1 = ex.getPath().toString();
				String str2 = str1.replace(", ", "/");
				pathstring = str2.substring(1, str2.length() - 1);
				

				textField.setText("/" + pathstring);
				textField.setFont(new Font("Alias", Font.BOLD, 12));
				string = ex.getPath().getLastPathComponent().toString();

				data.clear();
				if (list != null)
					list.removeAll();
				for (int i = 0; i < ana.node.size(); i++) {
					if (string.equals(ana.node.get(i).uppername)
							&& lev == ana.node.get(i).level)
						data.add(ana.node.get(i).name);
					//list.add(ana.node.get(i).name,null);	    
				}*/

				final JPopupMenu popupm = new JPopupMenu();
				JMenuItem modifym = new JMenuItem("下载");

				modifym.setActionCommand("下载");
				modifym.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						new SaveFiledialog();
					}
				});
				JMenuItem propertym = new JMenuItem("属性");
				propertym.setActionCommand("属性");
				propertym.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						// new SaveFiledialog();
						property pro = new property();
						pro.setVisible(true);
					}
				});

				JMenuItem uploadm = new JMenuItem("上传");
				uploadm.setActionCommand("上传");
				uploadm.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						// new SaveFiledialog();
						
						//如何处理路径问题
						//
						FileDialog my1 = new FileDialog(display.this, "打开",
								FileDialog.LOAD);
						my1.setVisible(true);

						String mailbody = "" + " ";
						String subject = new String();
						subject = "/" + pathstring;
						int index = subject.indexOf(".");
						if (index == -1) {
							subject = subject.substring(5) + "/"
									+ my1.getFile();
							System.out.println(subject);
						} else {
							int index2 = subject.lastIndexOf("/");
							subject = subject.substring(5, index2 + 1)
									+ my1.getFile();
							System.out.println(subject);
						}

						sendMail themail = new sendMail("smtp.sina.com.cn");
						themail.setNeedAuth(true);

						if (themail.setSubject(subject) == false)
							return;
						if (themail.setBody(mailbody) == false)
							return;
						if (themail.setTo("wangq_30@sina.com") == false)
							return;
						if (themail.setFrom("wangq_30@sina.com") == false)
							return;
						if (themail.addFileAffix(my1.getDirectory()
								+ my1.getFile()) == false)
							return;
						themail.setNamePass("wangq_30", "901170");
						if (themail.sendout() == false)
							return;
						try {
							PrintWriter pw = new PrintWriter(
									new FileOutputStream("name.txt", true),
									true);
							pw.println(subject + ";");//时间没办法写进去怎么办？？？？
							pw.close();
						} catch (Exception ee) {
							ee.printStackTrace();
						}
						dispose();
						display dis = new display();
						dis.setVisible(true);
						tree.addSelectionPath(path);
						//以上一行是否有问题？？？？？？？？？？？？？？？
					}
				});
				JMenuItem zhankaim = new JMenuItem("打开");
				zhankaim.setActionCommand("打开");
				zhankaim.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						//tree.expandPath(path);
						
					}
				});
				popupm.add(zhankaim);
				popupm.add(modifym);
				popupm.add(uploadm);
				popupm.add(propertym);

			
				// 1: 左键选中然后再右键去操作——————————能否变成邮件直接选中、操作？
				list.addMouseListener(new MouseAdapter() {
					public void mousePressed(MouseEvent e) {
						if (e.getButton() == e.BUTTON3) { //BUTTON3是鼠标右键
							//DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
							//		.getLastSelectedPathComponent();
							popupm.show(e.getComponent(), e.getX(), e.getY());
						}
					}
				});
			
				//list.setListData(data);
			}
		});	
		getContentPane().add(list);
		/////////////////////////////////////////////////////
		
		final JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		final JMenu fileMenu = new JMenu();
		fileMenu.setText("文件夹");
		menuBar.add(fileMenu);

		final JMenuItem newItemMenuItem = new JMenuItem();
		newItemMenuItem.setText("下载");
		fileMenu.add(newItemMenuItem);
		newItemMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new SaveFiledialog();
			}
		});

		final JMenuItem newItemMenuItem_2 = new JMenuItem();
		newItemMenuItem_2.setText("更新");
		fileMenu.add(newItemMenuItem_2);

		final JMenuItem newItemMenuItem_3 = new JMenuItem();
		newItemMenuItem_3.setText("属性");
		fileMenu.add(newItemMenuItem_3);
		newItemMenuItem_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				property pro2 = new property();
				pro2.setVisible(true);
			}
		});

		final JMenu menu = new JMenu();
		menu.setText("关 于");
		menuBar.add(menu);

		final JMenuItem newItemMenuItem_4 = new JMenuItem();
		newItemMenuItem_4.setText("关于软件");
		menu.add(newItemMenuItem_4);
		newItemMenuItem_4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				soft_intro s = new soft_intro();
				s.setVisible(true);
			}
		});

		final JMenuItem newItemMenuItem_5 = new JMenuItem();
		newItemMenuItem_5.setText("关于作者");
		newItemMenuItem_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				author_intro au = new author_intro();
				au.setVisible(true);
			}
		});
		menu.add(newItemMenuItem_5);

		textField = new JTextField();
		textField.setBounds(69, -2, 475, 29);
		getContentPane().add(textField);

		final JLabel label = new JLabel();
		label.setText(" 路 径：");
		label.setBounds(12, -1, 51, 27);
		getContentPane().add(label);

		//标签“向上”并添加鼠标点击的事件处理
		final JLabel label_1 = new JLabel();
		label_1.setIcon(new ImageIcon("resources/arrow_up.png"));
		label_1.setText("向上");
		label_1.setBounds(550, 0, 51, 27);
		label_1.addMouseListener(new MouseListener() {
			public void mouseClicked(MouseEvent e) {
				tree.clearSelection();
				tree.addSelectionPath(path.getParentPath());

			}

			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub	
			}

			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
			}

			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
			}

			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
			}
		});
		getContentPane().add(label_1);

		Date date = new Date();
		SimpleDateFormat stdf = new SimpleDateFormat("访问时间：yyyy年MM月dd日");
		String dates = stdf.format(date);
		final JLabel label_2 = new JLabel();
		label_2.setForeground(new Color(0, 0, 0));
		label_2.setBackground(new Color(135, 206, 235));
		label_2.setFont(new Font("Alias", Font.BOLD, 15));
		label_2
				.setText("          欢  迎  使  用  本  软  件  ！！             访问时间：2009年05月18日");
		label_2.setBounds(27, 439, 609, 36);

		getContentPane().add(label_2);

	}

	//创建JTree的方法
	public JTree createTree() {

		//一般构造方法
		JTree tree;

		int depth = 0;//深度
		int length = 0;
		int length1 = 0;
		//
		
		for (int j = 0; j < ana.node.size(); j++) {
			if (depth < ana.node.get(j).level)
				depth = ana.node.get(j).level;
		}

		DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
		for (int j = 1; j < depth; j++) {
			//清空存放各级目录名称的列表
			//	s.clear();
			//	t.clear();
			for (int i = 0; i < ana.node.size(); i++) {
				if (ana.node.get(i).level == 1 && j == 1) {
					s.add(new DefaultMutableTreeNode(ana.node.get(i).name));
					//t.add(ana.node.get(i).name);
				}
				if (ana.node.get(i).level == j) {
					//	s.add(new DefaultMutableTreeNode(ana.node.get(i).name));
					t.add(ana.node.get(i).name);
				}
			}

			length1 = s.size();

			for (int k = length; k < length1; k++) {

				if (j == 1)
					root.add(s.get(k));
				for (int m = 1; m < ana.node.size(); m++) {
					if (ana.node.get(m).uppername.equals(t.get(k))
							&& ana.node.get(m).level == j + 1) {
						DefaultMutableTreeNode n = new DefaultMutableTreeNode(
								ana.node.get(m).name);

						s.get(k).add(n);
						s.add(n);
					}
				}
			}

			length = length1;
			//      System.out.println(length+"  "+s.size()+" "+t.size());
			//   for(int g=0;g<t.size();g++)
			//System.out.println(t.get(g));
			//   System.out.println(s.size());

		}

		DefaultTreeModel treeModel = new DefaultTreeModel(root);
		root.setAllowsChildren(true);
		tree = new JTree(treeModel);

		DefaultTreeCellRenderer treeRender = new DefaultTreeCellRenderer();
		treeRender.setOpaque(true);
		tree.setCellRenderer(treeRender);
		return tree;
	}
}

/**
 * @设置展开时每个结点图标的类
 * @author 
 *
 */
class MyCellRenderer extends JLabel implements ListCellRenderer {
	final static ImageIcon longIcon = new ImageIcon("resources/folder_star.png");
	final static ImageIcon shortIcon = new ImageIcon(
			"resources/page_white_star.png");

	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
		String s = value.toString();
		int flag = 0;
		setText(s);
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '.') {
				setIcon(shortIcon);
				flag = 1;
			}
		}
		if (flag == 0)
			setIcon(longIcon);
		if (isSelected) {
			setBackground(list.getSelectionBackground());
			setForeground(list.getSelectionForeground());
		} else {

			setBackground(list.getBackground());
			setForeground(list.getForeground());
		}
		setEnabled(list.isEnabled());
		setFont(list.getFont());
		setOpaque(true);
		return this;
	}

}

/**
 * @download files
 * @author
 */

class SaveFiledialog extends JFrame {

	JLabel proper = new JLabel();
	JLabel label3 = new JLabel();
	JLabel labell = new JLabel();
	JLabel label5 = new JLabel();
	JButton selectButton = new JButton("保存");
	JButton cancelButton = new JButton("取消");

	public SaveFiledialog() {

		setTitle("文件下载");
		setSize(400, 250);

		proper.setSize(250, 100);
		proper.setText("您想保存此文件吗？");
		proper.setFont(new Font("Alias", Font.BOLD, 20));
		label3.setText("     文件名：" + display.string);
		label3.setFont(new Font("Alias", Font.BOLD, 12));
		labell.setText("     文件路径：" + display.pathstring);
		labell.setFont(new Font("Alias", Font.BOLD, 12));
		label5.setText("     日期：2009年05年18日");
		label5.setFont(new Font("Alias", Font.BOLD, 12));
		int w1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
		int h2 = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
		this.setLocation((w1 - this.getSize().width) / 2,
				(h2 - this.getSize().height) / 2);

		Panel panel1 = new Panel();
		panel1.add(proper);
		setLayout(new GridLayout(5, 1));
		add(proper);
		add(label3);
		add(labell);
		add(label5);
		Panel panel = new Panel();
		//panel.setLayout(new GridLayout(1,2));
		panel.add(selectButton);
		panel.add(cancelButton);
		add(panel);

		selectButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				dispose();
				FileDialog my = new FileDialog(SaveFiledialog.this, "保存",
						FileDialog.SAVE);
				int w = (int) Toolkit.getDefaultToolkit().getScreenSize()
						.getWidth();
				int h = (int) Toolkit.getDefaultToolkit().getScreenSize()
						.getHeight();
				my.setLocation((w - my.getSize().width) / 2,
						(h - my.getSize().height) / 2);
				System.out.println(display.downpathstring);

				my.setFile(display.downstring);
				my.setVisible(true);

				String directory = my.getDirectory();
				System.out.println(directory);
				try {

					String str = new String();
					String subjct = new String();
					BufferedReader in = new BufferedReader(new FileReader(
							"name.txt"));
					//new analyser();
					//ParseMimeMessage pmm = null;

					// System.out.println(display.pathstring.substring(4, display.pathstring.length()));
					for (int i = 0; (str = in.readLine()) != null; i++) {
						//pmm = new ParseMimeMessage((MimeMessage) analyser.message[i]);
						int indexx = str.indexOf(";");
						subjct = str.substring(0, indexx);
						if (subjct.indexOf(display.downpathstring.substring(4,
								display.downpathstring.length())) != -1) {
							System.out.println("开始保存文件！");

							ParseMimeMessage mm = new ParseMimeMessage();
							mm.download(i, directory);
							JDialog my2 = new JDialog();
							JLabel label5 = new JLabel("文件已经成功保存在" + directory
									+ "中！");
							my2.add(label5);
							my2.setSize(300, 100);
							int w4 = (int) Toolkit.getDefaultToolkit()
									.getScreenSize().getWidth();
							int h4 = (int) Toolkit.getDefaultToolkit()
									.getScreenSize().getHeight();
							my2.setLocation((w4 - my.getSize().width) / 2,
									(h4 - my.getSize().height) / 2);
							my2.setVisible(true);
						}
					}

					in.close();
				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		});

		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		//setSize(300,100);
		setVisible(true);
	}
}
